package com.qlyl.modules.information.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.qlyl.common.api.vo.Result;
import com.qlyl.common.constant.CommonCheckStatus;
import com.qlyl.common.constant.CommonConstant;
import com.qlyl.common.constant.ErrorConstant;
import com.qlyl.common.system.api.ISysBaseAPI;
import com.qlyl.common.system.util.JwtUtil;
import com.qlyl.common.util.PasswordUtil;
import com.qlyl.common.util.RedisUtil;
import com.qlyl.common.util.oConvertUtils;
import com.qlyl.modules.information.entity.AppUser;
import com.qlyl.modules.information.entity.Consumers;
import com.qlyl.modules.information.entity.EthWallet;
import com.qlyl.modules.information.service.IAppUserService;
import com.qlyl.modules.information.service.IConsumersService;
import com.qlyl.modules.information.service.IEthService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;

@Slf4j
@RequestMapping("/appapi")
@RestController
public class AppUserApiContronller {

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private IAppUserService appUserService;
    @Autowired
    private IConsumersService consumersService;
    @Autowired
    private IEthService iEthService;


    @Autowired
    private ISysBaseAPI sysBaseAPI;

    /**
             * 用户注册接口
             *
             * @param jsonObject
             * @param appUser
             * @return
             */
            @PostMapping("/register")
            public Result<JSONObject> appUserRegister(@RequestBody JSONObject jsonObject, AppUser appUser) {
                Result<JSONObject> result = new Result<JSONObject>();
                String cphone = jsonObject.getString("cphone");
                String smscode = jsonObject.getString("smscode");
                Object code = redisUtil.get(cphone);
                String username = jsonObject.getString("username");
                String password = jsonObject.getString("password");
                String email = jsonObject.getString("email");
                if(StringUtils.isBlank(username)||StringUtils.isBlank(password)){
                    return Result.error(ErrorConstant.REQUIREID_PARAMETER_IS_NULL);
                }

                AppUser user = appUserService.getAppUserByName(username);
                if (user != null) {
                    return result.error500("用户名已注册");
                }
                AppUser user2 = appUserService.getAppUserByPhone(cphone);
                if (user2 != null) {
                    return result.error500("该手机号已注册");
                }
                AppUser user3 = appUserService.getAppUserUserByEmail(email);
                if (user3 != null) {
                    return result.error500("邮箱已被注册");
                }

        //短信验证暂未开通
//        if (!smscode.equals(code)) {
//            result.setMessage("手机验证码错误");
//            result.setSuccess(false);
//            return result;
//        }

        try {
            appUser.setCreateTime(new Date());// 设置创建时间
            String salt = oConvertUtils.randomGen(8);
            String passwordEncode = PasswordUtil.encrypt(username, password, salt);
            appUser.setSalt(salt);
            appUser.setUsername(username);
            appUser.setPassword(passwordEncode);
            appUser.setEmail(email);
            appUser.setCphone(cphone);

            //生成区块链钱包
            EthWallet ethWallet = appUserService.createWallet();
            appUser.setWalletId(ethWallet.getId());
            appUserService.save(appUser);
            // 给刚创建的钱包转一笔ether
            iEthService.rechargeEthWalletByAsyncAndFree(ethWallet.getAddress());
            result.success("注册成功");
        } catch (Exception e) {
            result.error500("注册失败");
        }
        return result;
    }

    /**
     * app登录_账号密码登录
     *
     * @param
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/applogin", method = RequestMethod.POST)
    public Result<JSONObject> mLogin(@RequestBody JSONObject jsonObject) throws Exception {
        Result<JSONObject> result = new Result<JSONObject>();
        String username = jsonObject.getString("username");
        String password = jsonObject.getString("password");

        //1. 校验用户是否有效
        AppUser appUser = appUserService.getAppUserByName(username);
        result = appUserService.checkUserIsEffective(appUser);
        if (!result.isSuccess()) {
            return result;
        }

        //2. 校验用户名或密码是否正确
        String userpassword = PasswordUtil.encrypt(username, password, appUser.getSalt());
        String appPassword = appUser.getPassword();
        if (!appPassword.equals(userpassword)) {
            result.error500("用户名或密码错误");
            return result;
        }

        //加公司名称（不想写关联查询）
        Consumers consumers = consumersService.getById(appUser.getConsumersId());
        if(consumers!=null){
            appUser.setCompanyName(consumers.getCompanyName());
        }


        JSONObject obj = new JSONObject();
        //用户登录信息
        obj.put("userInfo", appUser);

        // 生成token
        String token = JwtUtil.sign(username, appPassword);
        // 设置超时时间
        redisUtil.set(CommonConstant.PREFIX_APPUSER_TOKEN + token, token);
        redisUtil.expire(CommonConstant.PREFIX_APPUSER_TOKEN + token, JwtUtil.EXPIRE_TIME * 2 / 1000);
        //token 信息
        obj.put("token", token);
        result.setResult(obj);
        result.setSuccess(true);
        result.setCode(200);
        sysBaseAPI.addLog("用户名: " + username + ",登录成功[移动端]！", CommonConstant.LOG_TYPE_1, null);
        return result;
    }


    /**
     * 接触绑定公司
     *
     * @param
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/unbound", method = RequestMethod.GET)
    public Result<?> unbound(String userid) {
        AppUser appUser = appUserService.getById(userid);
        if(appUser!=null && appUser.getUserStatus() == 1 ){
            this.appUserService.update(new AppUser().setBindingStatus(Integer.valueOf(CommonCheckStatus.Auth_UNCHECK)).setConsumersId(""),
                    new UpdateWrapper<AppUser>().lambda().eq(AppUser::getId, userid));
            this.consumersService.update(new Consumers().setBindingStatus(Integer.valueOf(CommonCheckStatus.Auth_UNCHECK)).setBindingUserid(""),
                    new UpdateWrapper<Consumers>().lambda().eq(Consumers::getId, appUser.getConsumersId()));
        }else{
            return Result.error(ErrorConstant.NOT_BANGDING_CONSUMERS);
        }
        return Result.ok("解除绑定成功！");
    }
}
